<?php
function get_books() {
	/*
	return array(array( 'id' => 1,
						'title' => 'Всадник без головы',
						'price' => 100),
				array( 'id' => 2,
						'title' => 'Франкенштейн',
						'price' => 101),
						array( 'id' => 3,
						'title' => 'Сильмариллион',
						'price' => 150),
						array( 'id' => 4,
						'title' => 'Великий Гетсби',
						'price' => 99.9),
				);
	*/
	$db = connectdb();
	$query = "SELECT * FROM books";
	$res = mysql_query($query);
	$books = array();
	while($book = mysql_fetch_array($res)) {
		$books[] = $book;
	}
	return $books;
}

function get_book($id) {
	$db = connectdb();
	$query = "SELECT * FROM books WHERE id = $id";
	$res = mysql_query($query);
	return mysql_fetch_array($res);
}

function auth() {
	session_start();
	if(!isset($_SESSION['login'])){ 
		if( isset($_COOKIE['login']) &&
			isset($_COOKIE['pass_hash'])) {
			$login = $_COOKIE['login'];
			$pass_hash = $_COOKIE['pass_hash'];
			if(check_user($login, $pass_hash)) {
				$_SESSION['login'] = $login;
			}
		}
	} else {
		$login = $_SESSION['login'];
	}
	return $login;
}

function check_user($login, $hash) {
	$db = connectdb();
	$query = "SELECT * FROM users 
			  WHERE 
				login = '$login' AND
				pass_hash = sha1('$hash')";
	$res = mysql_query($query);
	return mysql_num_rows($res);
}

function reg_user($login, $pass) {
	if($login == '' || $pass == '') {
		return 'Empty login or pass';
	}
	$db = connectdb();
	$query = "SELECT * FROM users WHERE login = '$login'";
	$res = mysql_query($query, $db);
	if(mysql_num_rows($res) > 0) {
		return 'Login exists';
	}
	$query = "INSERT INTO users(login, pass_hash) 
					VALUES('$login',sha1('$pass'))";
	if(!mysql_query($query)) {
		return 'DB error. Try later';
	}
	return 0;
}

function connectdb() {
	$db = mysql_connect('localhost', 'root', '');
	mysql_select_db('blacks_books');
	return $db;
}
?>